﻿namespace Renci.iRods.Studio.Modules.Explorer.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Renci.iRods.Studio.Common.BaseClasses;
    using Microsoft.Practices.ServiceLocation;
    using Renci.iRods.Studio.Modules.Explorer.Events;
    using Microsoft.Practices.Prism.Events;
    using Renci.iRods.Studio.Modules.Explorer.Models;
    using Renci.iRods.Studio.Common.Events;

    public class MetadataDockableViewModel : ViewModelBase
    {
        private IRodsConnection _connection;
        public IEnumerable<MetadataModel> Metadata { get; private set; }

        public MetadataDockableViewModel()
        {
            var eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
            var connectionChangedEvent = eventAggregator.GetEvent<ConnectionChnagedEvent>();
            connectionChangedEvent.Subscribe(OnConnectionChanged);
            
            var selectedObjectChangedEvent = eventAggregator.GetEvent<SelectedObjectChangedEvent>();
            selectedObjectChangedEvent.Subscribe(OnSelectedObjectChanged);
        }

        private void OnConnectionChanged(IRodsConnection connection)
        {
            this._connection = connection;
        }

        private void OnSelectedObjectChanged(object selectedObject)
        {
            var item = selectedObject as ExplorerItemModel;

            if (item != null && this._connection != null)
            {                
                this.Metadata = item.Metadata.ToList();
            }
            else
            {
                this.Metadata = null;
            }

            this.NotifyOfPropertyChange(() => this.Metadata);
        }

    }
}
